package com.xiaomage.view.draw11

import android.content.Context
import android.graphics.*
import android.util.Log
import android.view.MotionEvent
import android.view.View

/**
 * Created by Administrator on 2018/1/7.
 */
class MyView(context: Context):View(context) {
    private val paint=getPaint()
    private val path=Path()
    private var previousX=0f
    private var previousY=0f
    private  var srcBitmap:Bitmap = BitmapFactory.decodeResource(resources,
            R.drawable.dog)
    private var bottomBitmap=BitmapFactory.decodeResource(resources,
            R.drawable.bottom)
    private val dstBitmap=Bitmap.createBitmap(
            500,500,Bitmap.Config.ARGB_8888
    )
    init {
        //设置软加载
        setLayerType(View.LAYER_TYPE_SOFTWARE,null)
    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //绘制底部
        canvas.drawBitmap(bottomBitmap,0f,0f,paint)

        //保存图层
        val layoutId=canvas.saveLayer(0f,0f,
                width.toFloat(),height.toFloat(),paint)

        //先把手指轨迹画到目标Bitmap上
        var c=Canvas(dstBitmap)
         c.drawPath(path,paint)

        //然后把目标图像画到画布上
        canvas.drawBitmap(dstBitmap,0f, 0f,paint)

        //计算原区域图像区域
        paint.xfermode = PorterDuffXfermode(
                PorterDuff.Mode.SRC_OUT
        )
        canvas.drawBitmap(srcBitmap,0f,0f,paint)

        paint.xfermode=null

        //还原图层
        canvas.restoreToCount(layoutId)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when(event.action){
            MotionEvent.ACTION_DOWN->{
                path.moveTo(event.x,event.y)
                previousX=event.x
                previousY=event.y
                return true
            }
            MotionEvent.ACTION_MOVE->{
                val endX=(previousX+event.x)/2
                val endY=(previousY+event.y)/2
                path.quadTo(previousX,previousY,endX,endY)

                previousX=event.x
                previousY=event.y

            }
        }
        postInvalidate()
        return super.onTouchEvent(event)
    }
    private fun getPaint(): Paint {
        val paint =Paint()
        paint.strokeWidth=45f
        paint.color=Color.RED
        return paint
    }
}